
// 加载回收站项目
function loadRecycleBinItems() {
    showLoader();
    
    fetch('RecycleBinServlet?action=list&userId=' + currentUserId)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            console.log(data);
            // 确保传入的是 data.data 数组
            renderRecycleBinItems(data.data);
            hideLoader();
        })
        .catch(error => {
            hideLoader();
            console.error('加载回收站项目失败:', error);
            showMessage('加载回收站项目失败，请重试', 'error');
            
            // 加载失败时显示测试数据
            const demoItems = [
                {
                    item_id: 1,
                    original_id: 101,
                    item_name: "王小明",
                    item_type: "card",
                    original_location: "我的名片夹",
                    owner_id: 1,
                    item_size: "2KB",
                    deleted_at: "2025-04-25 10:30:45",
                    last_edited_at: "2025-04-24 15:20:10"
                },
                {
                    item_id: 2,
                    original_id: 5,
                    item_name: "项目合作伙伴",
                    item_type: "folder",
                    original_location: "/",
                    owner_id: 1,
                    item_size: "15KB",
                    deleted_at: "2025-04-26 09:15:30",
                    last_edited_at: "2025-04-25 16:45:22"
                }
            ];
            renderRecycleBinItems(demoItems);
        });
}


//渲染回收站项目
// 渲染回收站项目（修复版 - 添加批量操作支持）
function renderRecycleBinItems(items) {
    const container = document.getElementById('recycleItems');
    container.innerHTML = '';
    
    // 清空选中状态
    selectedRecycleItemIds = [];
    
    if (items && items.length > 0) {
        items.forEach(item => {
            const row = document.createElement('tr');
            row.dataset.id = item.itemId;
            row.dataset.type = item.itemType;
            row.dataset.name = item.itemName;
            
            const itemTypeDisplay = (item.itemType === 'CARD' || item.itemType === 'card') ? '名片' : '名片夹';
            const deletedAtDisplay = formatDateTime(item.deletedAt);
            const lastEditedAtDisplay = item.lastEditedAt ? formatDateTime(item.lastEditedAt) : '无编辑记录';
            
            let itemSize = item.itemSize || '未知';
            if (item.itemType === 'FOLDER' || item.itemType === 'folder') {
                itemSize = item.itemSize || '文件夹';
            }
            
            let originalLocation = item.originalLocation || '/';
            if (originalLocation === '/' || originalLocation === '') {
                originalLocation = '根目录';
            }
            
            row.innerHTML = 
                '<td><input type="checkbox" class="checkbox recycle-checkbox" data-id="' + item.itemId + '"></td>' +
                '<td>' + escapeHtml(item.itemName) + '</td>' +
                '<td>' + itemTypeDisplay + '</td>' +
                '<td>' + escapeHtml(originalLocation) + '</td>' +
                '<td>用户' + item.ownerId + '</td>' +
                '<td>' + itemSize + '</td>' +
                '<td>' + deletedAtDisplay + '</td>' +
                '<td>' + lastEditedAtDisplay + '</td>';
            
            container.appendChild(row);
            
            // 添加右键菜单事件（支持批量操作）
            row.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                showRecycleBinContextMenu(e, item.itemId, item.itemName);
            });
        });
        
        // 添加复选框变化事件
        document.querySelectorAll('.recycle-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const itemId = parseInt(this.dataset.id);
                
                if (this.checked) {
                    if (!selectedRecycleItemIds.includes(itemId)) {
                        selectedRecycleItemIds.push(itemId);
                    }
                } else {
                    selectedRecycleItemIds = selectedRecycleItemIds.filter(id => id !== itemId);
                }
                
                updateRecycleSelectAllState();
            });
        });
    } else {
        container.innerHTML = '<tr><td colspan="8" class="text-center">回收站中没有项目</td></tr>';
    }
}

// 添加HTML转义函数（如果还没有的话）
function escapeHtml(unsafe) {
    if (unsafe == null || unsafe === undefined) {
        return '';
    }
    return String(unsafe)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}



// 更新回收站全选框状态
function updateRecycleSelectAllState() {
    const totalCheckboxes = document.querySelectorAll('.recycle-checkbox').length;
    const checkedCount = document.querySelectorAll('.recycle-checkbox:checked').length;
    
    document.getElementById('recycleSelectAll').checked = totalCheckboxes > 0 && checkedCount === totalCheckboxes;
}

// 显示回收站右键菜单
// 显示回收站右键菜单（支持批量操作）
function showRecycleBinContextMenu(e, itemId, itemName) {
    // 检查当前点击的项目是否已选中，如果未选中则清空之前的选择并选中当前项目
    if (!selectedRecycleItemIds.includes(itemId)) {
        selectedRecycleItemIds = [itemId];
        // 更新复选框状态
        document.querySelectorAll('.recycle-checkbox').forEach(checkbox => {
            checkbox.checked = checkbox.dataset.id == itemId;
        });
        updateRecycleSelectAllState();
    }
    
    // 清除原有菜单项
    const contextMenu = document.getElementById('contextMenu');
    contextMenu.innerHTML = '';
    
    // 根据选中数量决定菜单文本
    const selectedCount = selectedRecycleItemIds.length;
    const isMultiple = selectedCount > 1;
    
    // 添加回收站菜单项
    const menuItems = [
        { 
            id: 'ctxRestore', 
            icon: 'undo', 
            text: isMultiple ? '还原选中的' + selectedCount + '个项目' : '还原',
            style: 'color: #28a745; font-weight: bold;'
        },
        { 
            id: 'ctxPermanentDelete', 
            icon: 'trash', 
            text: isMultiple ? '永久删除选中的' + selectedCount + '个项目' : '永久删除',
            style: 'color: #dc3545; font-weight: bold;'
        }
    ];
    
    menuItems.forEach(item => {
        const link = document.createElement('a');
        link.id = item.id;
        link.innerHTML = '<i class="fas fa-' + item.icon + ' me-2"></i> ' + item.text;
        
        if (item.style) {
            link.style.cssText = item.style;
        }
        
        link.addEventListener('click', () => {
            handleRecycleBinContextMenu(item.id, selectedRecycleItemIds);
        });
        
        contextMenu.appendChild(link);
    });
    
    // 设置菜单位置
    contextMenu.style.top = e.pageY + 'px';
    contextMenu.style.left = e.pageX + 'px';
    contextMenu.style.display = 'block';
}

//处理回收站右键菜单（支持批量操作）
function handleRecycleBinContextMenu(action, itemIds) {
    document.getElementById('contextMenu').style.display = 'none';
    
    const isMultiple = Array.isArray(itemIds) && itemIds.length > 1;
    
    switch (action) {
        case 'ctxRestore':
            // 批量还原确认
            const restoreMessage = isMultiple 
                ? '确定要还原选中的 ' + itemIds.length + ' 个项目吗？'
                : '确定要还原此项目吗？';
                
            if (confirm(restoreMessage)) {
                if (isMultiple) {
                    batchRestoreItems(itemIds);
                } else {
                    restoreRecycleBinItem(itemIds[0]);
                }
            }
            break;
        case 'ctxPermanentDelete':
            // 批量永久删除确认
            const deleteMessage = isMultiple 
                ? '确定要永久删除选中的 ' + itemIds.length + ' 个项目吗？此操作无法撤销！'
                : '确定要永久删除此项目吗？此操作无法撤销！';
                
            if (confirm(deleteMessage)) {
                if (isMultiple) {
                    batchPermanentDeleteItems(itemIds);
                } else {
                    deleteRecycleBinItem(itemIds[0]);
                }
            }
            break;
    }
}

//批量还原回收站项目
function batchRestoreItems(itemIds) {
    showLoader();
    
    console.log('批量还原项目 IDs:', itemIds);
    
    let completedCount = 0;
    let successCount = 0;
    const totalCount = itemIds.length;
    
    // 定义完成所有请求后的操作
    function onAllCompleted() {
        hideLoader();
        
        // 清空选中状态
        selectedRecycleItemIds = [];
        document.querySelectorAll('.recycle-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
        updateRecycleSelectAllState();
        
        loadRecycleBinItems();
        loadFolders();
        
        if (successCount > 0) {
            showMessage('成功还原了 ' + successCount + ' 个项目', 'success');
        } else {
            showMessage('还原操作失败', 'error');
        }
    }
    
    // 为每个选中的项目发送请求
    itemIds.forEach(itemId => {
        const formData = new FormData();
        formData.append('item_id', itemId);
        
        fetch('RecycleBinServlet?action=restore', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                successCount++;
            }
            completedCount++;
            if (completedCount === totalCount) {
                onAllCompleted();
            }
        })
        .catch(error => {
            console.error('还原项目失败:', error);
            completedCount++;
            if (completedCount === totalCount) {
                onAllCompleted();
            }
        });
    });
}


//批量永久删除回收站项目
function batchPermanentDeleteItems(itemIds) {
    showLoader();
    
    console.log('批量永久删除项目 IDs:', itemIds);
    
    const formData = new FormData();
    formData.append("itemIds", JSON.stringify(itemIds));
    
    fetch('RecycleBinServlet?action=batchDelete', {
        method: 'POST',
        body: formData,
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(data => {
        hideLoader();
        
        if (data.success) {
            // 清空选中状态
            selectedRecycleItemIds = [];
            document.querySelectorAll('.recycle-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            updateRecycleSelectAllState();
            
            loadRecycleBinItems();
            showMessage('成功永久删除了 ' + itemIds.length + ' 个项目', 'success');
        } else {
            showMessage('永久删除失败：' + data.message, 'error');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('批量永久删除失败:', error);
        showMessage('批量永久删除失败，请重试', 'error');
    });
}


// 还原回收站项目
function restoreRecycleBinItem(itemId, itemName) {
    showLoader();
    
    const formData = new FormData();
    formData.append('item_id', itemId);
    console.log("huanyuan id is :" + itemId);
    
    fetch('RecycleBinServlet?action=restore', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(data => {
        hideLoader();
        loadRecycleBinItems();
        loadFolders();
        showMessage('项目"' + itemName + '"已成功还原', 'success');
    })
    .catch(error => {
        hideLoader();
        console.error('还原项目失败:', error);
        showMessage('还原项目失败，请重试', 'error');
    });
}

// 永久删除回收站项目
function deleteRecycleBinItem(itemId, itemName) {
    showLoader();
    
    const formData = new FormData();
    formData.append('item_id', itemId);
    console.log("shanchu id is :" + itemId);
    
    fetch('RecycleBinServlet?action=delete', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(data => {
        hideLoader();
        loadRecycleBinItems();
        showMessage('项目"' + itemName + '"已永久删除', 'success');
    })
    .catch(error => {
        hideLoader();
        console.error('永久删除项目失败:', error);
        showMessage('永久删除项目失败，请重试', 'error');
    });
}

// 批量还原回收站项目
function restoreSelectedItems() {
    const checkboxes = document.querySelectorAll('.recycle-checkbox:checked');
    
    if (checkboxes.length === 0) {
        showMessage('请选择要还原的项目', 'error');
        return;
    }
    
    showLoader();
    
    // 创建一个计数器来跟踪完成的操作数量
    let completedCount = 0;
    const totalCount = checkboxes.length;
    
    // 定义完成所有请求后的操作
    function onAllCompleted() {
        hideLoader();
        loadRecycleBinItems();
        loadFolders();
        showMessage('已还原 ' + completedCount + ' 个项目', 'success');
    }
    
    // 为每个选中的项目发送请求
    checkboxes.forEach(checkbox => {
        const itemId = checkbox.dataset.id;
        
        const formData = new FormData();
        formData.append('item_id', itemId);
        
        fetch('RecycleBinServlet?action=restore', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            completedCount++;
            if (completedCount === totalCount) {
                onAllCompleted();
            }
        })
        .catch(error => {
            console.error('还原项目失败:', error);
            completedCount++;
            if (completedCount === totalCount) {
                onAllCompleted();
            }
        });
    });
}

// 清空回收站
function emptyRecycleBin() {
    showLoader();
    
    fetch('RecycleBinServlet?action=empty', {
        method: 'POST'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(data => {
        hideLoader();
        loadRecycleBinItems();
        showMessage('回收站已清空', 'success');
    })
    .catch(error => {
        hideLoader();
        console.error('清空回收站失败:', error);
        showMessage('清空回收站失败，请重试', 'error');
    });
}

//批量删除函数
function batchDeleteItems(itemIds) {
    const formData = new FormData();
    formData.append("action", "batchDelete");
    formData.append("itemIds", JSON.stringify(itemIds));  // 将 itemIds 作为 JSON 字符串传递

    fetch('RecycleBinServlet', {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage('永久删除成功', 'success');
            // 刷新页面或重新加载回收站列表
            loadRecycleBinItems();
        } else {
            showMessage('永久删除失败：' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('删除操作失败:', error);
        showMessage('永久删除失败，请重试', 'error');
    });
}

